package com.ybkj.daijia.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.SmsApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.mapper.SmsSendBlackRecordMapper;
import com.ybkj.daijia.server.mapper.SmsTempletMapper;
import com.ybkj.daijia.server.model.SmsRecord;
import com.ybkj.daijia.server.model.SmsSendBlackRecord;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.SmsService;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DefaultSmsService implements SmsService {

    private static final Logger logger = LoggerFactory.getLogger(DefaultMemberService.class);

    @Autowired
    private SmsApi smsApi;

    @Autowired
    private SmsTempletMapper smsTempletMapper;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private SmsSendBlackRecordMapper blackRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SmsTemplet insertSmsTemplate(String name, String type, SmsTemplet smsTemplet) {
        Result<SmsTemplet> result = smsApi.create(name, type, smsTemplet);
        smsTemplet = result.getResult();
        return smsTemplet;
    }

    @Override
    public SmsTemplet findByAlias(Long companyId, SmsType smsType) {
        return smsTempletMapper.selectByCompanyAndType(companyId, smsType);
    }

    @Override
    public SmsTemplet update(SmsTemplet smsTemplet) {
        smsApi.update(smsTemplet);
        return smsTemplet;
    }

    @Override
    public int sendSms(String phone, String alias, String variable, Long companyId, Integer type,
        String sign) {
        if (StringUtils.isNotBlank(sign)) {
            int amount = smsApi.sendSms(phone, alias, variable, companyId, type, sign);
            return amount;
        }
        return -1;
    }

    @Override
    public Long batchSendSms(String phones, String message) {
        return smsApi.batchSendSms(phones, message);
    }

    @Override
    public Page<SmsRecord> queryByParam(String phone, String appName, Long startTime,
        Long endTime) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        return smsApi
            .queryByParam(phone, appName, startTime, endTime, Long.valueOf(Pager.getPage()),
                Long.valueOf(Pager.getLimit()), pageable);
    }

    @Override
    public Page<Map<String, Object>> queryRechargeRecord(Integer page, Integer limit) {

        return smsApi.queryRechargeRecord(page, limit);
    }

    @Override
    public Long querySmsAppBalance() {
        return smsApi.querySmsAppBalance();
    }

    @Override
    public void sendSmsMsg(String IP, String phone, String code, Long companyId,
        String companyAbbreviation, String companySignName) {
        SmsTemplet templet = findByAlias(companyId, SmsType.companyCode);
//		if (templet == null) {
//			SmsTemplet smsTemplet = new SmsTemplet();
//			smsTemplet.setSmsType(SmsType.memberCode);
//			smsTemplet.setCompanyId(companyId);
//			smsTemplet.setContent("{\"公司名\":\""+companyAbbreviation+"\",\"验证码\":\""+code+"\"}");
//			insertSmsTemplate("memberCode", SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//		}

        if (null != templet
            && StringUtils.isNotBlank(templet.getContent())
            && StringUtils.isNotBlank(companyAbbreviation)
            && StringUtils.isNotBlank(companySignName)) {

            //int ret = sendSms(phone, "memberCode","{\"公司名\":\"" + companyAbbreviation + "\",\"验证码\":\"" + code + "\"}", companyId, 0, companySignName);
            //短信发送（改）
            JSONObject smsParam = new JSONObject();
            smsParam.put("companyName", companyAbbreviation);
            smsParam.put("code", code);
            int ret = sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(), companyId, 0,
                companySignName);
            logger.info("客户接受短信结果：" + ret);
        }
    }

    @Override
    public boolean SmsSendBlackRecordCallBack(String IP, String phone) {
        SmsSendBlackRecord record = blackRecordMapper.selectByPhoneAndIp(IP, phone);
        if (record == null) {
            return false;
        }
        Date date = new Date();
        record.setValid(true);
        record.setUpdated(date);
        record.setLasted(date);
        record.setAmount(0);
        record.setImageCode(null);
        blackRecordMapper.updateByPrimaryKey(record);
        return true;
    }

    @Override
    public SmsSendBlackRecord queryBlackRecordByIPAndPhone(String IP, String phone) {
        SmsSendBlackRecord record = blackRecordMapper.selectByPhoneAndIp(IP, phone);
        return record;
    }

    @Override
    public void updateBlackRecordById(SmsSendBlackRecord record) {
        blackRecordMapper.updateByPrimaryKey(record);
    }

    @Override
    public int isDangerForSendVCode(String IP, String phone, String imageCode) {
        // 根据手机号，IP地址获取数据库的发送记录
        SmsSendBlackRecord record = blackRecordMapper.selectByPhoneAndIp(IP, phone);

        // 如果没有该记录就新增一条记录
        if (null == record) {
            Date date = new Date();
            record = new SmsSendBlackRecord();
            record.setAmount(1);
            record.setCreated(date);
            record.setIpAdd(IP);
            record.setLasted(date);
            record.setPhone(phone);
            record.setUpdated(date);
            record.setValid(true);
            blackRecordMapper.insertRecord(record);
            return 1;
        }

        // 不为空，说明发送过，更新数据库请求次数++
        Date date = new Date();
        record.setUpdated(date);
        record.setLasted(date);
        record.setAmount(record.getAmount() + 1);
        blackRecordMapper.updateByPrimaryKey(record);

        int num = record.getAmount();

        /*
         * 注：这里我们只关心请求的次数和图片验证码是否验证，而不关心请求的间隔，请求间隔交给验证图片验证码去解决
         *    当请求间隔满足'归零'条件（时间间隔满足&&且图片验证码正确）时，他会将该条信息
         *    的数据回归原始状态，即请求次数会归零，图片验证码默认成功
         */

        // 小于等于三次，继续发送验证码
        if (num <= 3) {
            return 1;
        } else {

            // 大于三次，先跟新数据库的该手机，该IP的valid为未验证
            record.setValid(false);
            record.setUpdated(date);
            record.setLasted(date);
            blackRecordMapper.updateByPrimaryKey(record);

            // 接下来，我们就要验证图片验证码了
            String localImageCode = record.getImageCode();
            if (null == imageCode
                || imageCode.isEmpty()
                || null == localImageCode
                || localImageCode.isEmpty()) { // 图片验证码为空或者需要加载验证码
                return 2;
            } else { // 有图片验证码，验证

                if (localImageCode.equals(imageCode)) { // 验证成功，跟新库valid为已验证
                    record.setValid(true);
                    record.setUpdated(date);
                    record.setLasted(date);
                    blackRecordMapper.updateByPrimaryKey(record);
                    return 1;

                } else { // 否则没有验证成功，返回0，表示验证失败
                    return 0;
                }

            }
        }
    }

    @Override
    public boolean validateImgCode(String IP, String phone, String imageCode) {
        // 根据手机号，IP地址获取数据库的发送记录
        SmsSendBlackRecord record = blackRecordMapper.selectByPhoneAndIp(IP, phone);

        if (record == null) {
            return false;
        }

        // 验证图片验证码
        String localImageCode = record.getImageCode();
        if (localImageCode.equals(imageCode)) { // 验证成功，跟新库valid为已验证
            record.setValid(true);
            record.setUpdated(new Date());
            record.setLasted(new Date());
            blackRecordMapper.updateByPrimaryKey(record);
            return true;

        } else { // 否则没有验证成功，返回0，表示验证失败
            return false;
        }
    }
}